package com.scj.vue3springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.j2objc.annotations.AutoreleasePool;
import com.scj.vue3springboot.entity.SysRole;
import com.scj.vue3springboot.entity.SysRoleMenu;
import com.scj.vue3springboot.entity.SysUser;
import com.scj.vue3springboot.entity.vo.MenuVo;
import com.scj.vue3springboot.entity.vo.RoleMenuVo;
import com.scj.vue3springboot.enums.DelFlagEnum;
import com.scj.vue3springboot.enums.StatusEnum;
import com.scj.vue3springboot.mapper.SysRoleMenuMapper;
import com.scj.vue3springboot.service.SysRoleService;
import com.scj.vue3springboot.mapper.SysRoleMapper;
import com.scj.vue3springboot.util.DateUtil;
import com.scj.vue3springboot.util.JwtUtils;
import com.scj.vue3springboot.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 86182
* @description 针对表【sys_role(角色信息表)】的数据库操作Service实现
* @createDate 2023-10-11 11:09:09
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
    implements SysRoleService {

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public Result findAllUserInfo(Integer page, Integer limit, SysRole sysRole) {
        // 构建查询条件
        LambdaQueryWrapper<SysRole> slqw = new LambdaQueryWrapper<>();
        slqw.like(StringUtils.isNotBlank(sysRole.getRoleName()), SysRole::getRoleName, sysRole.getRoleName());
        slqw.like(StringUtils.isNotBlank(sysRole.getRemark()), SysRole::getRemark, sysRole.getRemark());

        // 设置分页信息
        Page<SysRole> pageObject = new Page<>(page, limit);

        // 执行带有分页的查询
        IPage<SysRole> rolePage = baseMapper.selectPage(pageObject, slqw);

        // 返回结果
        return Result.success("查询成功", rolePage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addRole(SysRole sysRole, String token) {
        // 判断角色名是否已经存在
        SysRole role = baseMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleName, sysRole.getRoleName()));
        if (role != null) {
            return Result.failure("该角色名称已存在");
        }

        // 通过token获取用户id
        Long tokenUserId= Long.valueOf(JwtUtils.validateJWT(token).getClaims().getId());
        String date = DateUtil.getNowDate();
        sysRole.setCreateBy(tokenUserId);
        sysRole.setCreateTime(date);
        sysRole.setUpdateBy(tokenUserId);
        sysRole.setUpdateTime(date);
        sysRole.setDelFlag(DelFlagEnum.NOT_DELETED.getCode());
        sysRole.setStatus(StatusEnum.NORMAL.getCode());

        baseMapper.insert(sysRole);
        return Result.success("添加成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateRole(SysRole sysRole, String token) {
        //判断角色名是否存在
        SysRole role = baseMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleName, sysRole.getRoleName()));
        if (role != null && !role.getRoleId().equals(sysRole.getRoleId())) {
            return Result.failure("该角色名称已存在");
        }

        // 通过token获取用户id
        Long tokenUserId= Long.valueOf(JwtUtils.validateJWT(token).getClaims().getId());
        sysRole.setUpdateBy(tokenUserId);
        sysRole.setUpdateTime(DateUtil.getNowDate());

        updateById(sysRole);
        return Result.success("修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteRole(Long roleId, String token) {
        // 通过token获取用户id
        Long tokenUserId= Long.valueOf(JwtUtils.validateJWT(token).getClaims().getId());
        UpdateWrapper<SysRole> suuw = new UpdateWrapper<>();
        suuw.set("update_by",tokenUserId);
        suuw.set("update_time",DateUtil.getNowDate());
        suuw.set("del_flag",DelFlagEnum.DELETED.getCode());
        suuw.eq("role_id",roleId);
        baseMapper.update(null,suuw);
        return Result.success("删除成功");
    }

    @Override
    public Result findAllRoleAndMenuRole(Long roleId) {
        List<MenuVo> list=baseMapper.findAllRoleAndMenuRole(roleId);
        // 使用 Stream 对 list 进行转换
        List<MenuVo> topLevelMenus = list.stream()
                .filter(menu -> menu.getParentId() ==0)
                .map(menu -> addChildMenus(menu, list))
                .collect(Collectors.toList());
        return Result.success("查询成功",topLevelMenus);
    }

    private MenuVo addChildMenus(MenuVo parent, List<MenuVo> allMenus) {
        List<MenuVo> children = allMenus.stream()
                .filter(menu -> menu.getParentId() != null && menu.getParentId().equals(parent.getMenuId()))
                .map(menu -> addChildMenus(menu, allMenus))
                .collect(Collectors.toList());

        parent.setChildren(children);
        return parent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addRoleMenu(RoleMenuVo roleMenuVo) {
        // 先删除角色菜单关联表中的数据
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleMenuVo.getRoleId()));

        // 再添加角色菜单关联表中的数据
        for (Long menuId : roleMenuVo.getMenuId()) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleMenuVo.getRoleId());
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuMapper.insert(sysRoleMenu);
        }
        return Result.success("设置成功");
    }
}




